import { defineStore } from 'pinia'
import { useSessionStorage } from '@vueuse/core'   //在 localStorage 或 sessionStorage 中存储和同步状态
import { store } from '@/store'
import { LoginParams } from '@/api/auth/types'
import { UserInfo } from '@/api/user/types'
import { loginApi } from '@/api/auth/index'
import { resetRouter } from '@/router'
import { usePermissionStoreHook } from '@/store/modules/permission'
import router from '@/router';

export const useUserStore = defineStore('user', () => {
    const user: UserInfo = {
        username: '',
        roles: [],
        perms: []
    }
    const geo = useSessionStorage('geo', 0)
    const token = useSessionStorage('X-token', '')

    function login(LogParams: LoginParams) {
        return new Promise<void>((resolve, reject) => {
            loginApi(LogParams)
                .then(async(response:any) => {  
                    if(response.code == 200){
                        user.username = response.data.username;
                        geo.value = response.data.geo;
                        token.value = response.data.token; 
                        //登录成功就获取路由权限
                        const permissionStore = usePermissionStoreHook()
                        const accessRoutes = await permissionStore.generateRoutes();
                        accessRoutes.forEach((route) => {
                            router.addRoute(route);
                        });
                    }            
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    function logout() {
        token.value = ''
        localStorage.removeItem('X-token')
        localStorage.removeItem('X-app_persisted_raw_routes')
    }

    function resetToken() {
        return new Promise<void>((resolve) => {
            token.value = ''
            resetRouter()
            resolve()
        })
    }

    return {
        user,
        token,
        geo,
        login,
        logout,
        resetToken
    }
})

export function useUserStoreHook() {
    return useUserStore(store)
}